package com.yangcb.workrecord.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ${DESCRIPTION}
 *
 * @author yangcb
 * @create 2017-10-09 15:13
 **/
@Component
public class MyRedisLua {

    @Autowired
    private JdbcTemplate jdbcTemplate;

//    public void seckill() {
//
//        ExecutorService executor = Executors.newFixedThreadPool(200);//20个线程池并发数
//        try {
//            final Jedis jedis = new Jedis("127.0.0.1", 6379);
//            jedis.set("stock", "5000");//设置起始的抢购数
//            jedis.close();
//            for (int i = 0; i < 100000; i++) {//设置1000个人来发起抢购
//                executor.execute(new MyRunnableLua("user-" + new Date().getTime(), jdbcTemplate));
//            }
//        } finally {
//            executor.shutdown();
//        }
//
//
//    }


    public void initStock() {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.set("stock", "5000");//设置起始的抢购数
        jedis.close();
    }


    public Map<String, Object> seckill() {
        Logger logger = LoggerFactory.getLogger(MyRunnable.class);
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        String script = "\n" +
                "local stock = redis.call('get', 'stock');\n" +
                "if tonumber(stock) >= 1 then\n" +
                "    redis.call(\"incrby\", 'stock', -1);\n" +
                "    return 1;\n" +
                "end\n" +
                "return nil;\n";
        String userinfo = "user-" + new Date().getTime();
        Object obj = jedis.eval(script);
        if (obj != null) {
            logger.info("秒杀成功：{},userinfo={}", obj, userinfo);
            try {
                jdbcTemplate.update("insert into seckill(userinfo,status,time) VALUES (?,?,?)", userinfo, 1, new Date());
            } catch (Exception e) {
                logger.info("错误信息---->{}", e.getMessage());
                jdbcTemplate.update("insert into seckill(userinfo,status,time) VALUES (?,?,?)", userinfo, 1, new Date());
            }
        } else {
            try {
                logger.info("秒杀失败：userinfo={}", userinfo);
                jdbcTemplate.update("insert into seckill(userinfo,status,time) VALUES (?,?,?)", userinfo, 0, new Date());
            } catch (Exception e) {
                logger.info("错误信息---->{}", e.getMessage());
                jdbcTemplate.update("insert into seckill(userinfo,status,time) VALUES (?,?,?)", userinfo, 0, new Date());
            }
        }

        jedis.close();

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", 200);
        result.put("msg", "SUCCESS");
        result.put("data", userinfo);

        return result;
    }

}


//class MyRunnableLua implements Runnable {
//    Logger logger = LoggerFactory.getLogger(MyRunnable.class);
//    Jedis jedis = new Jedis("127.0.0.1", 6379);
//    String script = "\n" +
//            "local stock = redis.call('get', 'stock');\n" +
//            "if tonumber(stock) >= 1 then\n" +
//            "    redis.call(\"incrby\", 'stock', -1);\n" +
//            "    return 1;\n" +
//            "end\n" +
//            "return nil;\n";
//
//    String userinfo;
//    JdbcTemplate jdbcTemplate;
//
//    public MyRunnableLua() {
//
//    }
//
//    public MyRunnableLua(String userinfo, JdbcTemplate jdbcTemplate) {
//        this.userinfo = userinfo;
//        this.jdbcTemplate = jdbcTemplate;
//    }
//
//    @Override
//    public void run() {
//        Object obj = jedis.eval(script);
//        if (obj != null) {
//            logger.info("秒杀成功：{},userinfo={}", obj, userinfo);
//            try{
//                jdbcTemplate.update("insert into seckill(userinfo,status,time) VALUES (?,?,?)", userinfo, 1, new Date());
//            }catch (Exception e){
//                logger.info("错误信息---->{}",e.getMessage());
//                jdbcTemplate.update("insert into seckill(userinfo,status,time) VALUES (?,?,?)", userinfo, 1, new Date());
//            }
//        } else {
//            try{
//            logger.info("秒杀失败：userinfo={}", userinfo);
//            jdbcTemplate.update("insert into seckill(userinfo,status,time) VALUES (?,?,?)", userinfo, 0, new Date());
//            }catch (Exception e){
//                logger.info("错误信息---->{}",e.getMessage());
//                jdbcTemplate.update("insert into seckill(userinfo,status,time) VALUES (?,?,?)", userinfo, 0, new Date());
//            }
//        }
//
//        jedis.close();
//    }
//
//
//}